const fs = require('fs')
const path = require('path')
const glob = require('glob')
const chalk = require('chalk')
const permissionMap = new Map()
const pattern = '*.route.js'
let hasReadFileSuccess = false

function getPermissionMap () {
  return new Promise(resolve => {
    glob(path.join(__dirname, `../routes/${pattern}`), (err, files) => {
      if (err) {
        console.error(chalk.red('匹配文件时出错：', err))
        resolve(permissionMap)
        return
      }
      // 创建一个 Promise 数组，每个 Promise 读取一个文件
      const promises = files.map(file => {
        return new Promise((resolve, reject) => {
          fs.readFile(file, 'utf8', (err, data) => {
            if (err) {
              reject(err)
              return
            }
            resolve(data)
          })
        })
      })

      // 所有文件读取完成后，执行相应操作
      Promise.all(promises)
        .then(results => {
          console.log(chalk.green('接口权限映射关系生成'))
          results.forEach(fileContent => {
            // 使用正则表达式提取注释信息
            const regex = /\/\*\*(.*?)\*\//gs
            const matches = fileContent.matchAll(regex)

            // 遍历匹配结果，提取注释信息对应的路由和权限码
            for (const match of matches) {
              const comment = match[1]
              // 提取路由信息
              const routeRegex = /@route\s+(.+)/
              const routeMatches = comment.match(routeRegex)

              // 提取权限码信息
              const accessRegex = /@access\s+(.*?)\s+/
              const accessMatches = comment.match(accessRegex)
              if (routeMatches && accessMatches) {
                const route = routeMatches[1]
                const path = '/api/v1' + route.split(' ').reverse().join(':')
                const accessCode = accessMatches[1]
                permissionMap.set(path, accessCode)
              }
            }
          })
          hasReadFileSuccess = true
          resolve(permissionMap)
        })
        .catch(error => {
          console.error(chalk.red('读取文件出错：', error))
          resolve(permissionMap)
        })
    })
  })
}

const awaitSetPermissionMap = async () => {
  if (hasReadFileSuccess) {
    return permissionMap
  }
  return getPermissionMap()
}

module.exports = awaitSetPermissionMap
